import Controller from "./Controller";
import {Request,Response} from 'express';
import Config from '../Config'
import Fs from 'fs-extra'
import admZip from 'adm-zip'
import { join as path_join } from 'path'
import md5 from 'md5'
class CreateTpl extends Controller
{
    constructor(req:Request,res:Response) {
        super(req,res);
    }

    /**
     * 创建项目目录
     */
    async create() {
        try {
            const tpl_id = this.HD.tpl_id;

            // 是否位第一次初始化运行
            let first_run = 0;

            // 1、先判断模板id是否创建了模板目录
           const Tpl = await this.first("tpl",{id:tpl_id}) as {dir:string}
            if(!Tpl.dir) {

                first_run = 1;

                // 2、创建目录
                const { dir,project_dir } = this.createDir(tpl_id)

                // 3、目录创建成功，数据目录dir字段内容
                await this.update("tpl",{id:tpl_id},{dir})

                // 4、解压小程序初始源码到项目目录下
                await this.unzipProject(project_dir) 

                // 5、创建src组件文件夹的软连接到模板目录
                // if(!Fs.existsSync(path_join(project_dir,"src","components"))) {
                //     Fs.symlinkSync(
                //         path_join(Config.root_dir,"components"),
                //         path_join(project_dir,"src","components"),
                //         "junction"
                //     )
                // }
            }
            this.response(200,{
                first_run
            }) 
        }catch(error:any) {
            this.response(error.code?error.code:402,[],error.message)
        }
    }

    /**
     * 创建目录
     */
    createDir(tpl_id:Number):{ dir:string,project_dir:string } 
    {
        const dir_name = md5(`${new Date().getTime()}${tpl_id}`)
        const dir_source = path_join("projects",dir_name)
        const project_dir = path_join(Config.data_dir,dir_source);
        if(!Fs.pathExistsSync(project_dir)) {
            Fs.mkdirsSync(project_dir)
        }
        if(!Fs.pathExistsSync(project_dir)) {
            throw new Error("创建目录失败");
        }
        return {
            dir: dir_source,
            project_dir
        };
    }

    /**
     * 解压初始源码包
     */
    unzipProject(project_dir:string):any {
        return new Promise((resolve,reject) => {
            const Zip = new admZip(`${Config.root_dir}/source.cool`);
            Zip.extractAllToAsync(project_dir,true,false,(error?: Error) => {
                if(error) {
                    reject(error)
                } else { 
                    resolve(true)
                }
            });
        })
    }

    
}

export default CreateTpl;